package com.hydra.baseui.recyclerlist;

import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

/**
 * 1、有多个type时继承getItemViewType
 * 2、如果继承getItemId，记得设置setHasStableIds(true)
 */
public abstract class BaseListAdapter<T, VH extends BaseItemHolder> extends RecyclerView.Adapter<VH> {

    protected List<T> mList;

    @Override
    public final VH onCreateViewHolder(ViewGroup parent, int viewType) {
        VH holder = buildViewHolder(parent, viewType);

        onViewHolderCreated(holder, parent, viewType);

        return holder;
    }

    protected abstract VH buildViewHolder(ViewGroup parent, int viewType);

    protected void onViewHolderCreated(VH holder, ViewGroup parent, int viewType) {
        //used when an item first created
    }

    public void insertData(List<T> list, int position, int count) {
        mList = list;
        notifyItemRangeInserted(position, count);
    }

    public void removeData(List<T> list, int position, int count) {
        mList = list;
        notifyItemRangeRemoved(position, count);
    }

    public void updateData(List<T> list, int position, int count) {
        mList = list;
        notifyItemRangeChanged(position, count);
    }

    public void moveData(List<T> list, int from, int to) {
        mList = list;
        notifyItemMoved(from, to);
    }

    public void setDatas(List<T> list) {
        mList = list;
        notifyDataSetChanged();
    }

    public List<T> getDatas() {
        return mList;
    }

    @Override
    public int getItemCount() {
        return null != mList ? mList.size() : 0;
    }

    @Nullable
    public T getItem(int position) {
        if (null != mList && position >= 0 && position < mList.size()) {
            return mList.get(position);
        }
        return null;
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);

        release();
    }

    public void release() {

    }
}
